package com.qf.service.impl;

import com.qf.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 根据用户名，查询用户对象（封装用户名、密码、权限）
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        com.qf.pojo.User user = userMapper.findByUsername(username);

        List<String> roles = user.getRoles();
        List<String> newRoles = new ArrayList<>();

        for (String role : roles) {
            String newRole = role.replaceAll("ROLE_", "");
            newRoles.add(newRole);
        }


        //要求前端传递的用户名为 zhangsan、密码为 123才可以登录，否则不能登录
        return User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                //role方法中设置的角色不允许以ROLE_开头
                .roles(newRoles.toArray(new String[]{}))
                .build();

    }
}
